package bearworker.zxl.service.impl;

import bearworker.zxl.dao.mapper.WxInterfaceLogMapper;
import bearworker.zxl.entity.StaticDataEntity;
import bearworker.zxl.entity.WxInterfaceLog;
import bearworker.zxl.service.WxService;
import bearworker.zxl.utils.CommUtil;
import bearworker.zxl.utils.CryptoUtil;
import bearworker.zxl.utils.XmlUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 逍遥的熊 on 2018/1/5.
 */
@Service("wx")
public class WxServiceImpl implements WxService{

    private Logger logger = Logger.getLogger(WxServiceImpl.class);

    private Map<String, Object> resMap = new HashMap<>();

    @Autowired
    private StaticDataEntity staticData;

    @Autowired
    private WxInterfaceLogMapper wxInterfaceLogMapper;

    public String wxStart(Map<String,String> params){
        logger.debug(params);
        String signature = params.get("signature");
        String openid = params.get("openid");
        String nonce = params.get("nonce");
        String timestamp = params.get("timestamp");
        String data = params.get("bodyStr");
        String wxToken = staticData.getWxToken();

        WxInterfaceLog interfaceLog = new WxInterfaceLog();

        interfaceLog.setSignature(signature);
        interfaceLog.setOpenid(openid);
        interfaceLog.setNonce(nonce);
        interfaceLog.setTimestamp(timestamp);
        interfaceLog.setBodystr(data);

        wxInterfaceLogMapper.insert(interfaceLog);

        String[] list = new String[]{wxToken,timestamp,nonce};
        Arrays.sort(list);

        StringBuilder sb = new StringBuilder();

        for(String a : list){
            sb.append(a);
        }

        String code = CryptoUtil.SHA1(sb.toString());
        logger.debug("code:"+code);
        logger.debug("source:"+signature);

        Map dataMap = XmlUtil.xmltoMap(data);

        logger.debug("data:"+dataMap);

        if(code.equals(signature)){
            return "success";
        }else {
            return "";
        }

    }


}
